package com.jp.spider.wbspider;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Function;
import com.jp.spider.util.HttpUtil;
import com.jp.spider.util.ImageByte;
import com.jp.spider.util.WebDriverProvider;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie2;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;


/**
 * Created by liujianpeng on 2017/6/9 0009.
 */
public class WbLoginSpder {

    static Logger logger = LoggerFactory.getLogger(WbLoginSpder.class);

    private String cjyUsername;
    private String cjyPassword;
    private String cjyCodeType;


    public WbLoginSpder() {
        try {
            Configuration conf = new PropertiesConfiguration("spider.properties");
            cjyUsername = conf.getString("uranus.spider.wb.chaojiying.username");
            cjyPassword = conf.getString("uranus.spider.wb.chaojiying.password");
            cjyCodeType = conf.getString("uranus.spider.wb.chaojiying.codeType");

        } catch (ConfigurationException e) {

        }
    }

    /**
     * 微博登录返回cookie
     * @param username
     * @param password
     * @return
     */
    public CookieStore login(String username, String password) {
        //可视化页面登录
        /*WebDriver driver = new ChromeDriver();
        driver.get("http://weibo.com/#_loginLayer_1504591284812");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        driver.findElement(By.name("username")).sendKeys(username);
        driver.findElement(By.name("password")).sendKeys(password);*/
        //pthantomJs后台登录
        PhantomJSDriver mobileWebDriver = WebDriverProvider.createWebDriver(true, true, HttpUtil.UA_PC_WINDOW, WebDriverProvider.WebDriverType.None);
        mobileWebDriver.navigate().to("http://www.weibo.com");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mobileWebDriver.findElement(By.name("username")).sendKeys(username);
        mobileWebDriver.findElement(By.name("password")).sendKeys(password);
        int cnt = 0;
        int retryCnt = 5;
        while (cnt++ < retryCnt) {
            try {
               String src= mobileWebDriver.findElement(By.xpath("//*[@id=\"pl_login_form\"]/div/div[3]/div[3]/a/img")).getAttribute("src");
                byte[] decode = new ImageByte().convertImageByByte(src);
                String s = ChaoJiYing.PostPic(cjyUsername, cjyPassword, cjyCodeType, "1005", "5", "0", "haha", decode);
                String encode = JSON.parseObject(s).getString("pic_str");
                if (StringUtils.isBlank(encode)) {
                    throw new RuntimeException(String.format("验证码平台出错了信息 s:%s", s));
                }
                mobileWebDriver.findElement(By.xpath("//*[@id=\"pl_login_form\"]/div/div[3]/div[3]/div/input")).clear();
                mobileWebDriver.findElement(By.xpath("//*[@id=\"pl_login_form\"]/div/div[3]/div[3]/div/input")).sendKeys(encode);
            } catch (Exception e) {
               logger.error("没有验证码");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            mobileWebDriver.findElement(By.xpath("//*[@id=\"pl_login_form\"]/div/div[3]/div[6]/a")).click();

            try {
                //成功
                WebElement element = mobileWebDriver.findElement(By.xpath("//*[@id=\"plc_top\"]/div/div/div[3]"));
                break;
            } catch (Exception e) {
                //登录错误提示
                String text = mobileWebDriver.findElement(By.cssSelector(".main_txt")).getText();
                logger.error(String.format("login account username [%s] password [%s]", username, password), text);
                if (text.contains("验证码")) {
                } else {
                    throw new RuntimeException(String.format("login account username [%s] password [%s] info[%s]", username, password, text));
                }
            }
        }
        //获取cookie
        CookieStore cookieStore = new BasicCookieStore();
        Cookie cookie = mobileWebDriver.manage().getCookieNamed("SUB");
        BasicClientCookie2 sub = new BasicClientCookie2(cookie.getName(), cookie.getValue());
        sub.setDomain("www.weibo.com");
        sub.setPath("/");
        BasicClientCookie2 sub1 = new BasicClientCookie2(cookie.getName(), cookie.getValue());
        sub1.setDomain(".weibo.com");
        sub1.setPath("/");
        BasicClientCookie2 sub2 = new BasicClientCookie2(cookie.getName(), cookie.getValue());
        sub2.setDomain(".weibo.cn");
        sub2.setPath("/");
        sub2.setExpiryDate(cookie.getExpiry());
        cookieStore.addCookie(sub);
        cookieStore.addCookie(sub1);
        cookieStore.addCookie(sub2);
        return cookieStore;
    }

    /**
     * jd登录
     */
    public static  void testjd(){
        WebDriver webDriver = new ChromeDriver();
        webDriver.get("https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F%3Fcu%3Dtrue%26utm_source%3Dbaidu-pinzhuan%26utm_medium%3Dcpc%26utm_campaign%3Dt_288551095_baidupinzhuan%26utm_term%3D0f3d30c8dba7459bb52f2eb5eba8ac7d_0_58a70a7425984241b6eb28b3a8c12271");
        webDriver.findElement(By.xpath("//*[@id=\"content\"]/div/div[1]/div/div[2]/a")).click();//点击切换账号登录
        webDriver.findElement(By.xpath("//*[@id=\"loginname\"]")).sendKeys("13621086797");
        webDriver.findElement(By.xpath("//*[@id=\"nloginpwd\"]")).sendKeys("13621086797");
        webDriver.findElement(By.xpath("//*[@id=\"loginsubmit\"]")).click();
    }

    /**
     * 极验拖动登录
     * @throws InterruptedException
     */
    public static void testyzm() throws InterruptedException {
        WebDriver crome = new ChromeDriver();
        WebDriverWait webDriverWait = new WebDriverWait(crome,10);
        crome.get("https://account.geetest.com/login");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        crome.findElement(By.xpath("//*[@id=\"email\"]")).sendKeys("123123");
        crome.findElement(By.xpath("//*[@id=\"password\"]")).sendKeys("12312312");
        crome.findElement(By.xpath("//*[@id=\"captcha\"]/div")).click();
        //等待验证码
        WebElement until = webDriverWait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.cssSelector(".geetest_slider_button"));
            }
        });

        //等待图片加载
        WebElement until2 = webDriverWait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.cssSelector(".geetest_canvas_fullbg geetest_fade geetest_absolute"));
            }
        });


/*        //点击截图
        until.click();
        Thread.sleep(2000);
        File scrFile = ((TakesScreenshot)crome).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(scrFile,new File("E:\\temp\\test.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        Actions actions = new Actions(crome);
        actions.clickAndHold(until).click();
        until2.getLocation();
        Thread.sleep(1500);
        int x = 50;
        for(int i=0;i<=5;i++){
            actions.dragAndDropBy(until,x,0);
            System.out.println(String.format("x=%s",x));
//            actions.clickAndHold(until).moveByOffset(x,1);
            actions.moveToElement(until).release().perform();
            x = x+8;
            //等待成功
            Thread.sleep(1000);
            WebElement success = webDriverWait.until(new Function<WebDriver, WebElement>() {
                public WebElement apply(WebDriver driver) {
                    return driver.findElement(By.cssSelector(".geetest_success_radar_tip_content"));
                }
            });
            System.out.println("+++++=:"+success.getText());
            if (success.getText().equals("验证成功")){
                System.out.println("验证成功");
                Thread.sleep(5000);
                break;
            }
            Thread.sleep(1000);
        }
//        crome.quit();
    }


    public static void main(String[] args) throws InterruptedException {
//        testyzm();
        WbLoginSpder wbLoginSpder = new WbLoginSpder();
//        CookieStore jianpeng58zp = wbLoginSpder.login("jianpeng.liu@pintuibao.cn", "jianpeng58zp");
        final CookieStore jianpeng58zp = wbLoginSpder.login("18676049373", "kknwur4026x");
        String title = HttpUtil.getPageSourceByClient("http://weibo.com/u/5918172619/home?wvr=5&lf=reg", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36", jianpeng58zp, "utf-8", "islogin", false);
        System.out.println(title);

//        System.out.println(wbLoginSpder.login("18676049373","kknwur4026x"));
//
//        String pageSourceByCookie = HttpUtil.getPageSourceByCookie("https://mp.weixin.qq.com/s?timestamp=1496988186&src=3&ver=1&signature=QfWH9v93srtRoiDNFMhWOJSe7kIThxgcQ0ekvKvVTqey8jBmKo1Dv6knTIsuzP721fR3Fccw5KMsTYIGixSjaZxAqky2U3orxELYlwi*RT-8sm-P0orZy6cY3oXf7HfRQjTP6Z1bzmgwjL*bNhQcuPvq6c9wY6Vy0-jJDFXnXR8=", null, false);
//        Document parse = Jsoup.parse(pageSourceByCookie);
//        System.out.println(pageSourceByCookie);
//        Comparator<String> stringComparator = (@NotNull String firsh, String second) -> Integer.compare(firsh.length(), second.length());
//        int compare = stringComparator.compare("1231", "1233");
//        System.out.println(compare);
//        BiFunction<String,String,Integer> comp = (String first,String second)->Integer.compare(first.length(),second.length());

    }

}
